package com.xinchao.ck_mips.logic;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.xinchao.ck_mips.App;
import com.xinchao.ck_mips.bean.ConfigBean;
import com.xinchao.ck_mips.bean.NewestProgramBean;
import com.xinchao.ck_mips.bean.ProgramBean;
import com.xinchao.ck_mips.bean.SourceInfoBean;
import com.xinchao.ck_mips.bean.UpgradeBean;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.ck_mips.dao.DaoUtil;
import com.xinchao.ck_mips.filedownload.SingleDownload;
import com.xinchao.ck_mips.impl.PlayModelImpl;
import com.xinchao.ck_mips.model.IDownCallbackListener;
import com.xinchao.ck_mips.model.IPlayModel;
import com.xinchao.ck_mips.utils.CheckOnOffUtil;
import com.xinchao.ck_mips.utils.DateUtil;
import com.xinchao.ck_mips.utils.DeviceUtil;
import com.xinchao.ck_mips.utils.FileUtils;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.devicemanage.BuildConfig;
import com.xinchao.devicemanage.DeviceManager;
import com.xinchao.devicemanage.util.DeviceInfoUtil;
import com.xinchao.devicemanage.util.MD5Util;
import com.xinchao.devicemanage.util.SharedPreferencesUtil;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created by wq on 2019/5/22.
 * 节目播放逻辑
 * 1.投放时间  开始时间+结束时间
 * 2.投放计划  1：普通 ；2：插播
 * 3.投放限制：all_day(所有);work_day（工作日）;work_end（周六+周日）
 */
public class PlayLogic {
    private List<SourceInfoBean> downList = new ArrayList<>();
    private List<SourceInfoBean> allList = new ArrayList<>();
    private List<String> versionList = new ArrayList<>();
    private static PlayLogic mInstance = null;
    private UpgradeBean bean;
    private String deviceOpenClose = "";

    private PlayLogic() {

    }

    public static PlayLogic getInstance() {
        if (null == mInstance) {
            synchronized (PlayLogic.class) {
                if (mInstance == null) {
                    mInstance = new PlayLogic();
                }
            }
        }

        return mInstance;
    }

    /**
     * 获取节目列表
     *
     * @return
     */
    public List<ProgramBean> getProgram(boolean isNeedDel) {
        //节目有更新，暂且不删除素材(删除的节目素材，有正在播放的节目素材)
        try {
            delTimeLimit(isNeedDel);
            List<ProgramBean> spotProgram = getSpotProgram();
            if (spotProgram != null && spotProgram.size() > 0) {
                Log.v("xika", "插播");
                return spotProgram;
            }

            if (DaoUtil.getProgramData() != null && DaoUtil.getProgramData().size() > 0) {
                List<ProgramBean> programList = new ArrayList<>();
                for (int i = 0; i < DaoUtil.getProgramData().size(); i++) {
                    ProgramBean bean = DaoUtil.getProgramData().get(i);
                    long time = System.currentTimeMillis();
                    if (bean.getPutinStartTime().longValue() <= time && time < bean.getPutinEndTime().longValue()) {
                        //只取在当前投放时间内的数据,本地文件已下载成功的数据
                        //兼容210老版本
                        if (bean.getPutinLevel().intValue() == 1 && isFileAvailable(bean)) {
                            if (bean.getPutinLimit().equals("all_day")) {
                                programList.add(bean);
                            } else if (bean.getPutinLimit().contains(DateUtil.getDayOfWeek())) {
                                //0,1,2,3,4,5,6
                                programList.add(bean);
                            } else if (bean.getPutinLimit().equals("work_day") && DateUtil.isWorkDay()) {
                                programList.add(bean);
                            } else if (bean.getPutinLimit().equals("work_end") && DateUtil.isWeekDay()) {
                                programList.add(bean);
                            }
                        }
                    }
                }

                //后台对节目列表已经排过序，不需要在mips重新排序
//                if (programList.size() > 0) {
//                    sortList(programList);
//                    return programList;
//                } else {
//                    return null;
//                }
                if(programList.size() <= 0){
                    return null;
                }else {
                    return programList;
                }
            }
        } catch (IndexOutOfBoundsException e) {
            return null;
        }

        return null;
    }

    /**
     * 删除过期数据
     */
    public void delTimeLimit(boolean isNeedDel) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (DaoUtil.getProgramData() != null && DaoUtil.getProgramData().size() > 0) {
                    for (int i = 0; i < DaoUtil.getProgramData().size(); i++) {
                        ProgramBean programBean = DaoUtil.getProgramData().get(i);
                        if (programBean.getPutinEndTime().longValue() < System.currentTimeMillis()) {
                            //节目投放时间已过，删除数据
                            DaoUtil.deleteByKey(programBean.getProgramVersion());
                            if (isNeedDel) {
                                String path = CK.VERSION_DIRS_PATH + File.separator + programBean.getProgramVersion();
                                FileUtils.delFolder(path);
                            }
                        }
                    }
                }
            }
        }).start();
    }

    /**
     * 获取插播节目
     * type:2
     *
     * @return
     */
    public List<ProgramBean> getSpotProgram() {
        if (DaoUtil.getProgramData() != null && DaoUtil.getProgramData().size() > 0) {
            List<ProgramBean> programList = new ArrayList<>();
            for (int i = 0; i < DaoUtil.getProgramData().size(); i++) {
                ProgramBean currentBean = DaoUtil.getProgramData().get(i);
                long nowTime = System.currentTimeMillis();
                if (currentBean.getPutinStartTime().longValue() <= nowTime && currentBean.getPutinEndTime().longValue() > nowTime) {
                    //当前节目时间在投放范围内
                    if (currentBean.getPutinLevel().intValue() == 2 && isFileAvailable(currentBean)) {
                        //有插播节目,优先播放插播节目
                        //兼容210老版本
                        if (currentBean.getPutinLimit().equals("all_day")) {
                            programList.add(currentBean);
                        } else if (currentBean.getPutinLimit().contains(DateUtil.getDayOfWeek())) {
                            programList.add(currentBean);
                        } else if (currentBean.getPutinLimit().equals("work_day") && DateUtil.isWorkDay()) {
                            programList.add(currentBean);
                        } else if (currentBean.getPutinLimit().equals("work_end") && DateUtil.isWeekDay()) {
                            programList.add(currentBean);
                        }
                    }
                }
            }

//            if (programList.size() > 0) {
//                sortList(programList);
//            }

            return programList;
        }

        return null;
    }

    /**
     * 判断节目下的素材（image,video）是否有效
     *
     * @param programBean
     * @return
     */
    public static boolean isFileAvailable(ProgramBean programBean) {
        boolean isAvailable = true;
        try {
            JSONArray sourceArray = new JSONArray(programBean.getFileInfo());
            if (sourceArray != null && sourceArray.length() > 0) {
                for (int n = 0; n < sourceArray.length(); n++) {
                    SourceInfoBean infoBean = new Gson().fromJson(sourceArray.getString(n), SourceInfoBean.class);
                    //web不需要下载素材
                    if (!infoBean.getFileType().equals("web")) {
                        infoBean.setProgramVersion(programBean.getProgramVersion());
                        String path = FileUtils.getProgramFilePath(infoBean);
                        File file = new File(path);
                        if (!file.exists() || !file.isFile() || path.contains(".temp")) {
                            isAvailable = false;
                            break;
                        }
                    }
                }
            } else {
                isAvailable = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isAvailable;
    }

    /**
     * 查找本地有效的节目素材，如果素材资源不存在，则依次下载
     */
    public void downFile() {
        if (DaoUtil.getProgramData() != null && DaoUtil.getProgramData().size() > 0) {
            List<SourceInfoBean> sourceList = new ArrayList<>();
            for (int i = 0; i < DaoUtil.getProgramData().size(); i++) {
                ProgramBean bean = DaoUtil.getProgramData().get(i);
                long time = System.currentTimeMillis();
                if (bean.getPutinStartTime().longValue() <= time && time < bean.getPutinEndTime().longValue()) {
                    //投放时间范围
                    try {
                        JSONArray sourceArray = new JSONArray(bean.getFileInfo());
                        if (sourceArray != null && sourceArray.length() > 0) {
                            for (int n = 0; n < sourceArray.length(); n++) {
                                SourceInfoBean infoBean = new Gson().fromJson(sourceArray.getString(n), SourceInfoBean.class);
                                //web不需要下载素材
                                if (!infoBean.getFileType().equals("web")) {
                                    infoBean.setProgramVersion(bean.getProgramVersion());
                                    String path = FileUtils.getProgramFilePath(infoBean);
                                    File file = new File(path);
                                    if (!file.exists() || !file.isFile() || !MD5Util.getFileMD5String(file).equals(infoBean.getMd5())) {
                                        sourceList.add(infoBean);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            if (sourceList.size() > 0) {
                //下载文件
                allList.clear();
                downList.clear();
                allList = sourceList;
                for (int i = 0; i < sourceList.size(); i++) {
                    downSource(sourceList.get(i));
                }
            }
        }
    }

    /**
     * 下载资源
     */
    public void downSource(SourceInfoBean bean) {
        SingleDownload.getInstance().downSingleFile(bean.getUrl(), FileUtils.getProgramFilePath(bean), new IDownCallbackListener() {
            @Override
            public void completed(String tag) {
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = bean;
                mHandler.sendMessage(msg);
            }

            @Override
            public void error(String url, Throwable t) {
            }

            @Override
            public void progressed() {

            }

            @Override
            public void pending() {
            }
        });
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                downList.add((SourceInfoBean) msg.obj);
            }

            if (downList.size() == allList.size()) {
                //文件全部下载完成
                new PlayModelImpl().uploadProgramStatus(0, ((SourceInfoBean) msg.obj).getProgramVersion(), "", new IPlayModel.IUploadProgramStatusCallbackListener() {
                    @Override
                    public void success() {
                    }

                    @Override
                    public void error(Throwable t) {
                    }
                });
            }
        }
    };

    /**
     * 根据投放时间对节目进行降序排序
     */
    public void sortList(List<ProgramBean> mList) {
        //排序
        Collections.sort(mList, new Comparator<ProgramBean>() {
            @Override
            public int compare(ProgramBean p1, ProgramBean p2) {
                if (p1.getPutinStartTime() < p2.getPutinStartTime()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });
    }

    /**
     * 删除过期文件节目
     */
    public void delLocalFile() {
        //本地数据库节目
        versionList.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ProgramBean> localList = DaoUtil.getProgramData();
                getLocalFile(new File(CK.VERSION_DIRS_PATH));
                if (localList != null && localList.size() > 0) {
                    if (versionList.size() > 0) {
                        List<String> programBeanList = new ArrayList<>();
                        for (int n = 0; n < localList.size(); n++) {
                            deleteSource(localList.get(n));
                            for (int t = 0; t < versionList.size(); t++) {
                                String version = versionList.get(t);
                                if (!version.equals(localList.get(n).getProgramVersion()) && !hasVersion(version)) {
                                    if (programBeanList.size() > 0) {
                                        boolean flag = false;
                                        for (int r = 0; r < programBeanList.size(); r++) {
                                            if (programBeanList.get(r).equals(version)) {
                                                flag = true;
                                                break;
                                            }
                                        }

                                        if (!flag) {
                                            programBeanList.add(version);
                                        }
                                    } else {
                                        programBeanList.add(version);
                                    }
                                }
                            }
                        }

                        if (programBeanList.size() > 0) {
                            for (int n = 0; n < programBeanList.size(); n++) {
                                //删除文件
                                String path = CK.VERSION_DIRS_PATH + File.separator + programBeanList.get(n);
                                FileUtils.delFolder(path);
                            }
                        }
                    }
                } else {
                    //直接删除文件
                    if (versionList.size() > 0) {
                        for (int i = 0; i < versionList.size(); i++) {
                            String path = CK.VERSION_DIRS_PATH + File.separator + versionList.get(i);
                            FileUtils.delFolder(path);
                        }
                    }
                }

                delAPK();
            }
        }).start();
    }

    /**
     * 删除单个节目下过期的素材资源
     */
    private void deleteSource(ProgramBean bean) {
        //节目路径
        try {
            String path = CK.VERSION_DIRS_PATH + File.separator + bean.getProgramVersion();
            //获取节目包下面的素材文件
            File file = new File(path);
            if (file.exists() && file.isDirectory()) {
                File[] files = file.listFiles();
                if (null != files && files.length > 0) {
                    JSONArray array = new JSONArray(bean.getFileInfo());
                    if (array != null && array.length() > 0) {
                        for (int i = 0; i < files.length; i++) {
                            boolean flag = true;
                            for (int n = 0; n < array.length(); n++) {
                                SourceInfoBean sourceInfoBean = new Gson().fromJson(array.getString(n), SourceInfoBean.class);
                                String url = sourceInfoBean.getUrl();
                                String fileName = url.substring(url.lastIndexOf("/") + 1);
                                if (files[i].getName().equals(fileName) || files[i].getName().contains(".temp")) {
                                    //文件名称相等或正在下载的文件不删除
                                    flag = true;
                                    break;
                                }

                                flag = false;
                            }

                            if (!flag) {
                                files[i].delete();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除过期文件
     */
    public void delAPK() {
        try {
            File file = new File(CK.APK_PATH);
            if (file.exists() && file.isDirectory()) {
                File[] list = file.listFiles();
                if (null != list && list.length > 0) {
                    for (int i = 0; i < list.length; i++) {
                        String apkname = list[i].getName().split("\\.")[0];
                        if (BuildConfig.VERSION_CODE > Integer.parseInt(apkname)) {
                            String path = CK.APK_PATH + File.separator + list[i].getName();
                            File childFile = new File(path);
                            if (childFile.isFile() && childFile.exists()) {
                                childFile.delete();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取节目文件夹下面的子文件数目
     *
     * @param programBean
     * @return
     */
    public int getVersionFilesNum(ProgramBean programBean) {
        String path = CK.VERSION_DIRS_PATH + File.separator + programBean.getProgramVersion();
        File file = new File(path);
        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                return 0;
            } else {
                int count = 0;
                for (int i = 0; i < files.length; i++) {
                    String fileName = files[i].getName();
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (!suffix.equals("temp")) {
                        count = count + 1;
                    }
                }
                return count;
            }
        }

        return 0;
    }

    /**
     * 删除本地文件
     *
     * @param file
     */
    public void getLocalFile(File file) {
        if (file.exists() && file.isDirectory()) {
            File[] list = file.listFiles();
            if (list != null && list.length != 0) {
                for (int i = 0; i < list.length; i++) {
                    versionList.add(list[i].getName());
                }
            }
        }
    }

    /**
     * 请求接口，获取服务器最新节目信息
     * 无效过期的数据从本地数据库删除，保留素材（需要删除的素材可能正在播放，暂且保留）
     */
    public void deleteDBProgram(NewestProgramBean bean) {
        List<ProgramBean> daoList = DaoUtil.getProgramData();
        if (daoList != null && daoList.size() > 0 && bean != null) {
            if (bean.getNewProgram().size() == 0) {
                //节目无数据，直接删除本地数据
                DaoUtil.deleteProgramData();
                return;
            }

            List<ProgramBean> mList = new ArrayList<>();
            for (int i = 0; i < bean.getNewProgram().size(); i++) {
                for (int n = 0; n < daoList.size(); n++) {
                    ProgramBean dbProgram = daoList.get(n);
                    ProgramBean serverProgram = bean.getNewProgram().get(i);

                    if (!dbProgram.getProgramVersion().equals(serverProgram.getProgramVersion()) && !hasProgram(bean.getNewProgram(), dbProgram)) {
                        if (mList.size() > 0) {
                            boolean flag = false;
                            for (int r = 0; r < mList.size(); r++) {
                                if (mList.get(r).getProgramVersion().equals(dbProgram.getProgramVersion())) {
                                    flag = true;
                                    break;
                                }
                            }

                            if (!flag) {
                                mList.add(dbProgram);
                            }
                        } else {
                            mList.add(dbProgram);
                        }
                    }
                }
            }

            if (mList.size() > 0) {
                for (int i = 0; i < mList.size(); i++) {
                    DaoUtil.deleteByKey(mList.get(i).getProgramVersion());//数据表删除数据记录
                }
            }
        }
    }

    /**
     * 当前列表是否包含
     *
     * @param currentVersion
     * @return
     */
    private boolean hasVersion(String currentVersion) {
        boolean flag = false;
        for (int t = 0; t < DaoUtil.getProgramData().size(); t++) {
            if (DaoUtil.getProgramData().get(t).getProgramVersion().equals(currentVersion)) {
                flag = true;
                break;
            }
        }

        return flag;
    }

    /**
     * 新节目是否存在本地数据库已存在的节目
     *
     * @param mlist 新节目
     * @return
     */
    private boolean hasProgram(List<ProgramBean> mlist, ProgramBean localProgram) {
        boolean flag = false;
        for (int t = 0; t < mlist.size(); t++) {
            if (mlist.get(t).getProgramVersion().equals(localProgram.getProgramVersion())) {
                flag = true;
                break;
            }
        }

        return flag;
    }

    /**
     * 设置定时升级apk时间
     *
     * @param bean
     * @return
     */
    public Calendar getCalendar(UpgradeBean bean) {
        Calendar calendar = Calendar.getInstance();
        long time = bean.getTimingTime().longValue();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd:HH:mm");
        String[] updateTime = sdf.format(date).split(":");
        calendar.set(Calendar.YEAR, Integer.parseInt(updateTime[0]));
        calendar.set(Calendar.MONTH, Integer.parseInt(updateTime[1]) - 1);
        calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(updateTime[2]));
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(updateTime[3]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(updateTime[4]));
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    /**
     * 获取今日是周几
     *
     * @return
     */
    public String get() {
        Calendar calendar = Calendar.getInstance();
        return String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 定时升级逻辑
     *
     * @param mAlarmManager
     * @param bean
     */
    public void upgradeAPK(AlarmManager mAlarmManager, UpgradeBean bean, Context mContext) {
        this.bean = bean;
        if (bean.getTimingTime().longValue() < System.currentTimeMillis()) {
            //定时升级时间已过，不执行升级
            return;
        }
        Intent apkIntent = new Intent("intent_alram_apk");
        PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, apkIntent, 0);
        if (Build.VERSION.SDK_INT < 19) {
            mAlarmManager.set(AlarmManager.RTC_WAKEUP, getCalendar(bean).getTimeInMillis(), pi);
        } else {
            mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, getCalendar(bean).getTimeInMillis(), pi);
        }
    }

    public void cancelAlarm(Context context, String action, int id) {
        Intent intent = new Intent(action);
        PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, PendingIntent
                .FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);
    }

    /**
     * 升级apk
     *
     * @param mContext
     * @param bean
     */
    public void upgradeAPK(Context mContext, UpgradeBean bean) {
        AlarmManager mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        //取消之前的任务
        cancelAlarm(mContext, "intent_alram_apk", 0);
        upgradeAPK(mAlarmManager, bean, mContext);
    }

    /**
     * 安装apk
     *
     * @param context
     */
    public void installAPK(Context context) {
        if (BuildConfig.VERSION_CODE >= bean.getVersionCode().intValue()) {
            return;
        }
        File apkFile = new File(FileUtils.getAPKFilePath(bean.getVersionCode()));
        if (apkFile.isFile() && apkFile.exists()) {
            DeviceUtil.installApp(apkFile.getAbsolutePath(), context);
        }
    }

    /**
     * 后台下发指令，设置开关机时间逻辑
     * 设置定时开关机逻辑
     */
    public void setServerOnOffTime(Context mContext, ConfigBean bean) {
        try {
            //设置定时开关机逻辑
            if (TextUtils.isEmpty(bean.getTimeShutdown()) || TextUtils.isEmpty(bean.getTimeBoot()) || TextUtils.isEmpty(bean.getNonWorkDayTimeShutdown()) || TextUtils.isEmpty(bean.getNonWorkDayTimeBoot())) {
                return;
            }

            if (!TextUtils.isEmpty(bean.getTimeBoot()) && !TextUtils.isEmpty(bean.getTimeShutdown())) {
                //工作日开关机时间
                ShareUtil.getInstance().saveWorkDayOnTime(bean.getTimeBoot());
                ShareUtil.getInstance().saveWorkDayOffTime(bean.getTimeShutdown());
            }

            if (!TextUtils.isEmpty(bean.getNonWorkDayTimeBoot()) && !TextUtils.isEmpty(bean.getNonWorkDayTimeShutdown())) {
                //周末开关机时间
                ShareUtil.getInstance().saveWeekDayOnTime(bean.getNonWorkDayTimeBoot());
                ShareUtil.getInstance().saveWeekDayOffTime(bean.getNonWorkDayTimeShutdown());
            }

            if (DateUtil.isMonDayToThursDay()) {
                //周一到周四
                if (DateUtil.getWorkDayOnTime().length != 0) {
                    setDeviceOnOff(mContext, bean.getTimeBoot(), bean.getTimeShutdown(), true);
                    if (DeviceManager.iBaseMachine == null) {
                        DeviceManager.iBaseMachine = App.iBaseMachine;
                    }
                    checkOnOffTime(mContext);
                }
            } else if (DateUtil.isFriday()) {
                //周五
                if (DateUtil.getWorkDayOnTime().length != 0) {
                    //不在开机时间范围内
                    int fri_onHour = Integer.parseInt(DateUtil.getWorkDayOnTime()[0]);//开机时间
                    int fri_onMinute = Integer.parseInt(DateUtil.getWorkDayOnTime()[1]);//开机分钟
                    int fri_offHour = Integer.parseInt(DateUtil.getWorkDayOffTime()[0]);//关机小时时间
                    int fri_offMin = Integer.parseInt(DateUtil.getWorkDayOffTime()[1]);//关机分钟时间
                    if ((fri_onHour > DateUtil.getNowHour() && (fri_onHour - DateUtil.getNowHour() > 1))
                            || (fri_onHour > DateUtil.getNowHour() && (fri_onHour - DateUtil.getNowHour() == 1) && (fri_onMinute - DateUtil.getNowMinute() > -50))
                            || (fri_onHour == DateUtil.getNowHour() && fri_onMinute > DateUtil.getNowMinute() && (fri_onMinute - DateUtil.getNowMinute() > 10))) {
                        //不在开机时间范围内（当前时间小于开机时间）
                        setDeviceOnOff(mContext, bean.getTimeBoot(), bean.getTimeShutdown(), true);
                        if (DeviceManager.iBaseMachine == null) {
                            DeviceManager.iBaseMachine = App.iBaseMachine;
                        }
                        //倒计时关机
                        checkOnOffTime(mContext);
                    } else if (fri_offHour < DateUtil.getNowHour() || (fri_offHour == DateUtil.getNowHour() && fri_offMin <= DateUtil.getNowMinute())) {
                        //不在开机时间范围内（当前时间大于关机时间）
                        //设置开机时间为周六开机时间,倒计时关机
                        setDeviceOnOff(mContext, bean.getNonWorkDayTimeBoot(), bean.getTimeShutdown(), true);
                        if (DeviceManager.iBaseMachine == null) {
                            DeviceManager.iBaseMachine = App.iBaseMachine;
                        }
                        checkOnOffTime(mContext);
                    } else {
                        //开机时间范围内
                        //设置开机时间为周六开机时间，不检测
                        setDeviceOnOff(mContext, bean.getNonWorkDayTimeBoot(), bean.getTimeShutdown(), true);
                    }
                }
            } else if (DateUtil.isSaturday()) {
                //周六
                if (DateUtil.getWeekDayOnTime().length != 0) {
                    setDeviceOnOff(mContext, bean.getNonWorkDayTimeBoot(), bean.getNonWorkDayTimeShutdown(), true);
                    if (DeviceManager.iBaseMachine == null) {
                        DeviceManager.iBaseMachine = App.iBaseMachine;
                    }
                    checkOnOffTime(mContext);
                }
            } else if (DateUtil.isSunday()) {
                //周日
                if (DateUtil.getWeekDayOnTime().length != 0) {
                    //不在开机时间范围内
                    int sun_onhour = Integer.parseInt(DateUtil.getWeekDayOnTime()[0]);//周六开机小时时间
                    int sun_onmin = Integer.parseInt(DateUtil.getWeekDayOnTime()[1]);//周六开机分钟时间
                    int sun_offhour = Integer.parseInt(DateUtil.getWeekDayOffTime()[0]);//周六关机小时时间
                    int sun_offmin = Integer.parseInt(DateUtil.getWeekDayOffTime()[1]);//周六关机分钟时间
                    if ((sun_onhour > DateUtil.getNowHour() && sun_onhour - DateUtil.getNowHour() > 1)
                            || (sun_onhour > DateUtil.getNowHour() && (sun_onhour - DateUtil.getNowHour()) == 1 && (sun_onmin - DateUtil.getNowMinute() > -50))
                            || (sun_onhour == DateUtil.getNowHour() && sun_onmin > DateUtil.getNowMinute() && (sun_onmin - DateUtil.getNowMinute() > 10))) {
                        //不在开机时间范围内，当前时间小于开机时间
                        //倒计时关机
                        setDeviceOnOff(mContext, bean.getNonWorkDayTimeBoot(), bean.getNonWorkDayTimeShutdown(), true);
                        if (DeviceManager.iBaseMachine == null) {
                            DeviceManager.iBaseMachine = App.iBaseMachine;
                        }
                        checkOnOffTime(mContext);
                    } else if (sun_offhour < DateUtil.getNowHour() || (sun_offhour == DateUtil.getNowHour() && sun_offmin <= DateUtil.getNowMinute())) {
                        //不在开机时间范围内，当前时间大于关机时间
                        //倒计时关机
                        setDeviceOnOff(mContext, bean.getTimeBoot(), bean.getNonWorkDayTimeShutdown(), true);
                        if (DeviceManager.iBaseMachine == null) {
                            DeviceManager.iBaseMachine = App.iBaseMachine;
                        }
                        checkOnOffTime(mContext);
                    } else {
                        //开机时间范围内
                        //设置开机时间为周一开机时间，不检测
                        setDeviceOnOff(mContext, bean.getTimeBoot(), bean.getNonWorkDayTimeShutdown(), true);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设备开机，设置工作日，非工作日开机时间逻辑
     *
     * @param mContext
     */
    public void setLocalOnOffTime(Context mContext) {
        try {
            if (TextUtils.isEmpty(ShareUtil.getInstance().getString(CK.WORK_DAY_ON_TIME, ""))
                    || TextUtils.isEmpty(ShareUtil.getInstance().getString(CK.WORK_DAY_OFF_TIME, ""))
                    || TextUtils.isEmpty(ShareUtil.getInstance().getString(CK.WEEK_DAY_ON_TIME, ""))
                    || TextUtils.isEmpty(ShareUtil.getInstance().getString(CK.WEEK_DAY_OFF_TIME, ""))) {
                //检测默认开关机时间（工作日、非工作日时间一致）
                if (DeviceManager.iBaseMachine == null) {
                    DeviceManager.iBaseMachine = App.iBaseMachine;
                }
                checkOnOffTime(mContext);
                return;
            }

            if (DateUtil.isMonDayToThursDay()) {
                //周一到周四
                setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WORK_DAY_ON_TIME, ""),
                        ShareUtil.getInstance().getString(CK.WORK_DAY_OFF_TIME, ""), false);
                if (DeviceManager.iBaseMachine == null) {
                    DeviceManager.iBaseMachine = App.iBaseMachine;
                }
                checkOnOffTime(mContext);
            } else if (DateUtil.isSaturday()) {
                //周六
                setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WEEK_DAY_ON_TIME, ""),
                        ShareUtil.getInstance().getString(CK.WEEK_DAY_OFF_TIME, ""), false);
                if (DeviceManager.iBaseMachine == null) {
                    DeviceManager.iBaseMachine = App.iBaseMachine;
                }
                checkOnOffTime(mContext);
            } else if (DateUtil.isFriday()) {
                //周五
                int fri_onhour = Integer.parseInt(DateUtil.getWorkDayOnTime()[0]);
                int fri_onminute = Integer.parseInt(DateUtil.getWorkDayOnTime()[1]);
                int fri_offhour = Integer.parseInt(DateUtil.getWorkDayOffTime()[0]);
                int fri_offmin = Integer.parseInt(DateUtil.getWorkDayOffTime()[1]);
                if ((fri_onhour > DateUtil.getNowHour() && (fri_onhour - DateUtil.getNowHour() > 1))
                        || (fri_onhour > DateUtil.getNowHour() && (fri_onhour - DateUtil.getNowHour() == 1) && (fri_onminute - DateUtil.getNowMinute() > -50))
                        || (fri_onhour == DateUtil.getNowHour() && fri_onminute > DateUtil.getNowMinute() && (fri_onminute - DateUtil.getNowMinute() > 10))) {
                    //不在开机时间范围内，当前时间小于开机时间
                    //倒计时关机
                    setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WORK_DAY_ON_TIME, ""),
                            ShareUtil.getInstance().getString(CK.WORK_DAY_OFF_TIME, ""), false);
                    if (DeviceManager.iBaseMachine == null) {
                        DeviceManager.iBaseMachine = App.iBaseMachine;
                    }
                    checkOnOffTime(mContext);
                } else if (fri_offhour < DateUtil.getNowHour() || (fri_offhour == DateUtil.getNowHour() && fri_offmin <= DateUtil.getNowMinute())) {
                    //不在开机时间范围内，当前时间大于关机时间
                    //倒计时关机
                    setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WEEK_DAY_ON_TIME, ""),
                            ShareUtil.getInstance().getString(CK.WORK_DAY_OFF_TIME, ""), false);
                    if (DeviceManager.iBaseMachine == null) {
                        DeviceManager.iBaseMachine = App.iBaseMachine;
                    }
                    checkOnOffTime(mContext);
                } else {
                    //开机时间范围内
                    //设置开机时间为周六开机时间，不检测
                    setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WEEK_DAY_ON_TIME, ""),
                            ShareUtil.getInstance().getString(CK.WORK_DAY_OFF_TIME, ""), false);
                }
            } else if (DateUtil.isSunday()) {
                //周日
                int sun_onhour = Integer.parseInt(DateUtil.getWeekDayOnTime()[0]);
                int sun_onminute = Integer.parseInt(DateUtil.getWeekDayOnTime()[1]);
                int sun_offhour = Integer.parseInt(DateUtil.getWeekDayOffTime()[0]);
                int sun_offmin = Integer.parseInt(DateUtil.getWeekDayOffTime()[1]);
                if ((sun_onhour > DateUtil.getNowHour() && sun_onhour - DateUtil.getNowHour() > 1)
                        || (sun_onhour > DateUtil.getNowHour() && (sun_onhour - DateUtil.getNowHour()) == 1 && (sun_onminute - DateUtil.getNowMinute() > -50))
                        || (sun_onhour == DateUtil.getNowHour() && sun_onminute > DateUtil.getNowMinute() && (sun_onminute - DateUtil.getNowMinute() > 10))) {
                    //不在开机时间范围内,当前时间小于开机时间
                    //倒计时关机
                    setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WEEK_DAY_ON_TIME, ""),
                            ShareUtil.getInstance().getString(CK.WEEK_DAY_OFF_TIME, ""), false);
                    if (DeviceManager.iBaseMachine == null) {
                        DeviceManager.iBaseMachine = App.iBaseMachine;
                    }
                    checkOnOffTime(mContext);
                } else if (sun_offhour < DateUtil.getNowHour() || (sun_offhour == DateUtil.getNowHour() && sun_offmin <= DateUtil.getNowMinute())) {
                    //不在开机时间范围内，当前时间大于关机时间
                    //倒计时关机
                    setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WORK_DAY_ON_TIME, ""),
                            ShareUtil.getInstance().getString(CK.WEEK_DAY_OFF_TIME, ""), false);
                    if (DeviceManager.iBaseMachine == null) {
                        DeviceManager.iBaseMachine = App.iBaseMachine;
                    }
                    checkOnOffTime(mContext);
                } else {
                    //开机时间范围内
                    //设置开机时间为周一开机时间，不检测
                    setDeviceOnOff(mContext, ShareUtil.getInstance().getString(CK.WORK_DAY_ON_TIME, ""),
                            ShareUtil.getInstance().getString(CK.WEEK_DAY_OFF_TIME, ""), false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查开关机时间
     *
     * @param mContext
     */
    public void checkOnOffTime(Context mContext) {
        if (Build.MODEL.contains("ZLP86Ni") || Build.MODEL.contains("IoT3288") || Build.MODEL.contains("3280") || Build.MODEL.contains("DS835")) {
            CheckOnOffUtil.getInstence(mContext, App.iBaseMachine).checkOnOffTime(null);
        }
    }

    /**
     * 设置开关机
     */
    public void setDeviceOnOff(Context mContext, String timeBoot, String timeShutDown, boolean flag) {
        if (deviceOpenClose.equals(""))
            deviceOpenClose = (String) SharedPreferencesUtil
                    .getInstance(mContext)
                    .getData(CK.DEVICE_OPEN_CLOSE, "");

        if (flag && deviceOpenClose.equals(timeBoot + timeShutDown)) {
            return;
        }
        SharedPreferencesUtil
                .getInstance(mContext)
                .saveData(CK.DEVICE_OPEN_CLOSE, timeBoot + timeShutDown);
        deviceOpenClose = timeBoot + timeShutDown;

        if (timeBoot.contains(":") && timeShutDown.contains(":")) {
            String[] on = timeBoot.split(":");
            String[] off = timeShutDown.split(":");
            if (on == null || off == null || on.length != 3 || off.length != 3) {
                return;
            }

            if (DeviceManager.iBaseMachine == null) {
                DeviceManager.iBaseMachine = App.iBaseMachine;
            }
            DeviceManager.iBaseMachine.setSwitchTime(Integer.parseInt(on[0]),
                    Integer.parseInt(on[1]),
                    Integer.parseInt(off[0]),
                    Integer.parseInt(off[1]));

            DeviceInfoUtil.getInstance(mContext).saveDeviceOnOff(Integer.parseInt(on[0]),
                    Integer.parseInt(on[1]),
                    Integer.parseInt(off[0]),
                    Integer.parseInt(off[1]));
        }
    }

}
